package com.etown.lucene;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class FileScheduler {
		
	private final Timer timer;//定时器
	
	public FileScheduler() {
		timer = new Timer();
	}
	//是否维护线程
	public FileScheduler(boolean isDaemon) {
		timer = new Timer(isDaemon);
	}
	/**
	 * 为定时器执行可分配的任务
	 * @param task
	 * @param timeStep
	 */
	public void schedule(Runnable task,TimeStep timeStep) {
		Date time = timeStep.next();
		SchedulerTimeTask timerTask = new SchedulerTimeTask(task,timeStep);
		//在指定的时间执行指定的任务
		timer.schedule(timerTask, time);
	}
	/**
	 * 重新分配任务
	 * @param task
	 * @param timeStep
	 */
	public void reSchedule(Runnable task,TimeStep timeStep) {
		Date time = timeStep.next();
		SchedulerTimeTask timerTask = new SchedulerTimeTask(task,timeStep);
		timer.schedule(timerTask, time);
	}
	/**
	 * 停止计时器
	 */
	public void StopTime() {
		timer.cancel();
	}
	/**
	 * 内部类 定时任务
	 * @author AFI
	 *
	 */
	private class SchedulerTimeTask extends TimerTask {

		private Runnable task;
		private TimeStep timeStep;
		
		public SchedulerTimeTask(Runnable task,TimeStep timeStep) {
			this.task = task;
			this.timeStep = timeStep;
		}
		@Override
		public void run() {
			//执行指定任务
			task.run();
			//重新执行任务
			reSchedule(task, timeStep);
		}
		
	}
}
